import { Injectable } from "@angular/core";
import { ValidationErrors, ValidatorFn, AbstractControl } from "@angular/forms";
import { isEmail, isMobile, isPasswordPass, isTelPhone } from "../common/utils";

@Injectable({
  providedIn: "root",
})
export class ValidatorsRuleService {
  constructor() {}

  mobileRule(value: string): ValidationErrors | null {
    if (!value) {
      return null;
    }
    return isMobile(value) ? null : { message: "请输入正确的手机号" };
  }

  telPhoneRule(value: string): ValidationErrors | null {
    if (!value) {
      return null;
    }
    return isTelPhone(value) ? null : { message: "请输入正确的电话号码" };
  }

  emailRule(value: string): ValidationErrors | null {
    if (!value) {
      return null;
    }
    return isEmail(value) ? null : { message: "请输入正确的邮箱格式" };
  }

  passwordRule(value: string): ValidationErrors | null {
    if (!value) {
      return null;
    }
    return isPasswordPass(value)
      ? null
      : { message: "密码由6到20位大小写字母、数字或其他字符组成" };
  }

  // 邮箱校验
  public emailValidator(): ValidatorFn | null {
    return this.commonUtil(this.emailRule);
  }

  // 手机号码校验
  public mobileValidator(): ValidatorFn | null {
    return this.commonUtil(this.mobileRule);
  }

  // 密码校验
  public passwordValidator(): ValidatorFn | null {
    return this.commonUtil(this.passwordRule);
  }

  // 电话号码校验
  public telephoneValidator(): ValidatorFn {
    return this.commonUtil(this.telPhoneRule);
  }

  private commonUtil(
    ruleFun: (value: string) => ValidationErrors | null
  ): ValidatorFn {
    return (control: AbstractControl): ValidationErrors | null => {
      return ruleFun(control.value);
    };
  }
}
